<?
// Define Session Path
$session_path = "sessions";

/*
Function:	dbConnect()
Updated:	08/27/2007
Description:	Connects to the database using the varibale defined in header.php
*/
function dbConnect()
{
	require_once(".football.db.inc");
	//Connect TO The Database
	mysql_connect($dbhost,$dbusername,$dbpass) or die("Cannot connect to the football database.<br/>");
	//Open Database
	mysql_select_db($database) or die("Cannot select the database in Connect().<br/>");
}

/*
Function:	getWeek($League)
Updated:	03/11/2008
Description:	Returns current week in $League schedule by looking to see which week has no winners posted.
*/
function getWeek($League)
{
	//Get Current Week
	/*
	$SQL = "SELECT Week FROM ".$League."Schedule WHERE Winner='-' ORDER BY Week ASC";
	$weekresult = mysql_query($SQL) or die("Cannot query the database in getting week.<br/>");
	if($myrow = mysql_fetch_array($weekresult))
		$CurrWeek = $myrow["Week"];
	else
			$CurrWeek = 22;
	return ($CurrWeek);
	*/
	return 15;
}


/*
Function:	getSeasonYear($League)
Updated:	03/11/2008
Description:	Returns current season for $League.
*/
function getSeasonYear($League)
{
	$SQL = "SELECT GameDate, Week, GameNum FROM ".$League."Schedule WHERE Week = 1 AND GameNum = 1";
	$weekresult = mysql_query($SQL) or die("Cannot query the database in getting Season.<br/>");
	if($myrow = mysql_fetch_array($weekresult))
		$Season = date("Y",strtotime($myrow["GameDate"]));
	else
		$Season = date("Y");
	return ($Season);
}

/*
Function:	makeUserLink($ID)
Updated:	03/11/2008
Description:	Returns a link to the user's profile contianing the user's current username.
*/
function makeUserLink($ID)
{
	//Get Current Week
	$SQL = "SELECT Username FROM Users WHERE ID=$ID";
	$result = mysql_query($SQL) or die("Cannot query the database in making user link.<br/>");
	if($myrow = mysql_fetch_array($result))
		$html = "<a href=\"http://football.joshhughes.com/members.php?ID=$ID\" class=\"permLink\" title=\"See the profile on ".$myrow["Username"]."\">".$myrow["Username"]."</a>";

	return ($html);
}


/*
Function:	getMagicNum($week,$League)
Updated:	03/11/2008
Description:	Returns the MagicNumber for given week.
*/
function getMagicNum($week,$League)
{
	$MagicNum = 0;
	//Get Current Week
	$SQL = "SELECT MagicNum FROM ".$League."WeeklyWinner WHERE Week=$week";
	$weekresult = mysql_query($SQL) or die("Cannot query the database in getting magic number.<br/>$SQL");
	if($myrow = mysql_fetch_array($weekresult))
		if ($myrow["MagicNum"] != NULL)
			$MagicNum = $myrow["MagicNum"];
			
			
	if ($MagicNum > 0)
		return $MagicNum;
	else
		return "-";
}

/*
Function:	checkWeekBounds($Week)
Updated:	01/11/2006
Description:	Takes the current week and checks to make sure it is not less than 1 or > 21.
				It's impossible to have a 0 week and there are only 21 weeks of football
				including the playoffs.
*/
function checkWeekBounds($Weeknum)
{
	switch($Weeknum)
	{
		case ($Weeknum > 22)://Check to make sure weeks don't go above 22
			$Weeknum = 22;
			break;
		case ($Weeknum < 1)://Check to make sure weeks don't go below 1
			$Weeknum = 1;
			break;
		default :
			//DO nothing
	}
	return ($Weeknum);
}


/*
Function:	WeekDropDown()
Updated:	01/11/2006
Description:	Prints out a drop-down list for each week up to the current week.
*/
function WeekDropDown($Weeknum)
{
	echo "<select name=\"Weeknum\" onChange=\"WeekForm.submit()\"><option selected>A Week</Option>";
		for($i = 1; $i <= 22; $i++) {
			echo "<option value=\"".$i."\"";
			if($i == $Weeknum)
			    echo " selected";
			echo "> Week ".$i."</option>";
		}
	echo "</select>";
}

/*
Function:	getRowColor($row)
Updated:	12/18/2007
Description:	Returns a row color based on odd or even row.
*/
function getRowColor($row)
{
	if (($row % 2) == 0)
		return ("#FFFFFF");	//Even Row
	else 
		return ("#DDDDDD");	//Odd row
}

/*
Function:	getWeekBanner($Weeknum, $League)
Updated:	03/28/2008
Description:	Return a different string for the "week" banner of a page
				depending on the weeknum, and round of the playoffs.
*/
function getWeekBanner($Weeknum, $League)
{
	switch($Weeknum)
	{
		case ($Weeknum == 18):
			echo "Wild Card Playoff";
			break;
		case ($Weeknum == 19):
			echo "Divisional Playoff";
			break;
		case ($Weeknum == 20):
			echo "Conference Championships";
			break;
		case ($Weeknum == 21):
			echo "Super Bowl";
			break;
		case ($Weeknum == 22):
			echo "Pro Bowl";
			break;
		default :
			echo "$League Week $Weeknum";
	}
}

/*
Function:	gameInProgress($Weeknum,$League)
Updated:	03/11/2008
Description:	Return true if a game is (or should) be in progress at the moment
				the function is called.
*/
function gameInProgress($Weeknum,$League)
{

	$SQL = "SELECT * FROM ".$League."Schedule Where Week=".$Weeknum." AND PickEmailed=0 ORDER BY GameDate, GameTime";
	//Open Record Set using SQL Query
	$result = mysql_query($SQL) or die("Cannot query the database to see if game in progress.<br/>");
	do{
		if (($myrow["GameTime"] != "") && ($myrow["GameDate"] != ""))
		{
			$timeAdjust = 3; //Number of hours From GMT + or - to be added
			$timeAdjust += date("I");
			$timeAdjust *= 60;	//60 minutes in an hour
			$timeAdjust *= 60;	//60 seconds in an minute
//echo date("Ymd",strtotime($myrow["GameDate"]))." ... " . date("Hi",strtotime($myrow["GameTime"])) ." -- " . gmdate("Hi",time() - $timeAdjust) . "<br/>";
			if (
			(date("Ymd",strtotime($myrow["GameDate"])) < date("Ymd")) ||
			(date("Ymd",strtotime($myrow["GameDate"])) == date("Ymd")) &&
			(date("Hi",strtotime($myrow["GameTime"])) < gmdate("Hi",time() - $timeAdjust)))
			{//if game is being played right now.  User cannot make pick anymore.
				echo "GameDate = ".date("Ymd",strtotime($myrow["GameDate"])).", currently ".date("Ymd").".<br />";
				echo "GameTime = ".date("Hi",strtotime($myrow["GameTime"])).", currently ".gmdate("Hi",time() - $timeAdjust).".<br />";
				return true;
			}
		}
	}while($myrow = mysql_fetch_array($result));
	
	return false;
}

/*
Function:	getGameCount($Weeknum,$League)
Updated:	03/11/2008
Description:	Returns the number of games for this week; Most weeks have 16 games, 
	  (teams have Byes) some weeks have only 14 games, some 13.
*/
function getGameCount($Weeknum,$League)
{
	$GameCount = 0;
	$SQL = "SELECT COUNT(*) AS GameCount FROM ".$League."Schedule WHERE Week=".$Weeknum;
	$result = mysql_query($SQL) or die("Cannot query the database to get game count.<br/>");
	if($myrow = mysql_fetch_array($result))
		$GameCount = $myrow["GameCount"];
		
	return $GameCount;
}

/*
Function:	teamWon($team, $week)
Updated:	03/11/2008
Description:	True if the team won this week, false if they lost.
*/
function teamWon($team, $week, $League)
{
	$SQL = "SELECT Winner FROM ".$League."Schedule WHERE Winner='$team' AND Week=".$week;
	$result = mysql_query($SQL) or die("Cannot query the database to see if team won.<br/>");
	if (mysql_affected_rows() > 0)
		return true;
	else
		return false;
}

/*
Function:	setWeeklyWinner($Week, $League)
Updated:	03/11/2008
Description:	Finds the user who got the most correct picks for the given week.
				If multiple users got the same number correct, the MagicNumber is
				the tie breaker.  Closest without going over.
*/
function setWeeklyWinner($Week, $League)
{
	echo "Setting weekly winner<br/>";
	$query="SELECT GameNum, Winner FROM ".$League."Schedule Where (WEEK=".$Week.") ORDER BY GameNum";
	$doQuery=mysql_query($query);
	$numrows=mysql_num_rows($doQuery);
	$num = 1;
	if($numrows > 0)
	{
		while($results=mysql_fetch_array($doQuery))
		{
			$winners[$num]=$results['Winner'];
			$num++;
		}		
		//Get Data From Users Who Picked
		$UserPickedSQL = "SELECT * FROM ".$League."Picks WHERE Week=".$Week;
		$UserPickedresult = mysql_query($UserPickedSQL);
		$row = 0;		
		while($myrow = mysql_fetch_array($UserPickedresult))
		{
			if ($myrow["Week"] != "")
			{	
				$WeeklyScores[$row] = 0;
				$IDs[$row] = $myrow["UserID"];
				$MagicNum[$row] = $myrow["MagicNum"];
				for($j = 1; $j <= $numrows; $j++)
				{
					$pick = $myrow["Game".$j];
					if($winners[$j] != "-") 
						if($pick == $winners[$j])
							$WeeklyScores[$row]++;
				}
				$row++;
			}
		}
		
		// Sort by weekly score
		for($i=sizeof($WeeklyScores); $i>0; $i--)
		{
			for($i2=1; $i2 <= $i; $i2++)
			{
				if($WeeklyScores[$i2-1] < $WeeklyScores[$i2])
				{
					swapthese($WeeklyScores[$i2-1],$WeeklyScores[$i2]);
					swapthese($IDs[$i2-1],$IDs[$i2]);
					swapthese($MagicNum[$i2-1],$MagicNum[$i2]);
				}				
			}
		}
		
		//for($i=sizeof($WeeklyScores); $i>=0; $i--)
		//	echo "user# $IDs[$i] (MagicNum guess of $MagicNum[$i]) had a score of $WeeklyScores[$i] for week $Week<br/>";
			
		//prune out lower scores, only keep the most correct picks for the week.
		for($i=sizeof($WeeklyScores); $i>0; $i--)
		{
			if ($WeeklyScores[$i] < $WeeklyScores[0])
			{
				unset($WeeklyScores[$i]);
				unset($IDs[$i]);
				unset($MagicNum[$i]);
			}
		}
		
		//for($i=sizeof($WeeklyScores); $i>=0; $i--)
		//	echo "user# $IDs[$i] (MagicNum guess of $MagicNum[$i]) had a score of $WeeklyScores[$i] for week $Week<br/>";
		
		//Get This Weeks Magic Number, it also helps determine if week is truely over.
		$WeekOver = true;
		$result = mysql_query("SELECT MagicNum FROM ".$League."WeeklyWinner WHERE Week=$Week") or die("Cannot query the database to set magic number.<br/>");
		$myrow = mysql_fetch_array($result);
		if (($myrow["MagicNum"] != NULL) && ($myrow["MagicNum"] != ""))
			$WeekMagicNum = $myrow["MagicNum"];
		else
			$WeekOver = false; //week is not over if MagicNum has not been set
		
		if (sizeof($WeeklyScores) > 1)
		{	$j = 0;
			echo "Need sorted by MagicNum<br/>";			
			//Find if any MagicNum guesses are less than the WeekMagicNum
			for($i=sizeof($MagicNum); $i>=0; $i--)
			{
				if ($MagicNum[$i] == 0)  //Magic # Guesses of Zero DO NOT COUNT.
				{
					unset($IDs[$i]);
					unset($MagicNum[$i]);
				}
				else
				{
					if ($MagicNum[$i] <= $WeekMagicNum)
					{	
							$NewNumArray[$j] = $MagicNum[$i];
							$NewIDs[$j] = $IDs[$i];
							$j++;
					}
				}
			}
					
			if (sizeof($NewNumArray) > 0)
			{
				//Sort $NewNumArray descending.  The largest number will be closest to the MagicNum
				for($i=sizeof($NewNumArray); $i>0; $i--)
				{
					for($i2=1; $i2 <= $i; $i2++)
					{
						if($NewNumArray[$i2-1] < $NewNumArray[$i2])
						{
							swapthese($NewNumArray[$i2-1],$NewNumArray[$i2]);
							swapthese($NewIDs[$i2-1],$NewIDs[$i2]);
						}				
					}
				}
				$SQL = "UPDATE ".$League."WeeklyWinner SET UserID=".$NewIDs[0].",Score=".$WeeklyScores[0].", MagicGuess=".$NewNumArray[0]." WHERE Week=$Week";
			}
			else
			{
				echo "All user's MagicNum guess are over this week's MagicNum ($WeekMagicNum)<br/>";
				//Sort $MagicNum Array ascending. The smallest number will be closest to the MagicNum
				for($i=sizeof($MagicNum); $i>0; $i--)
				{
					for($i2=1; $i2 <= $i; $i2++)
					{
						if($MagicNum[$i2-1] > $MagicNum[$i2])
						{
							swapthese($MagicNum[$i2-1],$MagicNum[$i2]);
							swapthese($IDs[$i2-1],$IDs[$i2]);
						}				
					}
				}
				$SQL = "UPDATE ".$League."WeeklyWinner SET UserID=".$IDs[1].",Score=".$WeeklyScores[0].", MagicGuess=".$MagicNum[1]." WHERE Week=$Week";
			}
		}
		else
		{
			echo "only one person had the best score for this week<br/>";
			$SQL = "UPDATE ".$League."WeeklyWinner SET UserID=".$IDs[0].",Score=".$WeeklyScores[0].", MagicGuess=".$MagicNum[0]." WHERE Week=$Week";
		}
		echo "$SQL<br/>";
		
		if ($WeekOver)
			mysql_query($SQL);//echo "Do some DB updating here";
		else
			echo "Week not over yet";
	
	}
}

/*
Function:	make_seed()
Updated:	01/11/2006
Description:	Makes Seed for a random number
*/
function make_seed() {
    list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}


/*
Function:	getUsername($value);
Updated:	12/06/2007
Description:	Get Username From UserID
*/
function getUsername($value) {
    $UserName = "Unknown ID";
	$SQL = "SELECT Username FROM Users Where ID=".$value;
	$result = mysql_query($SQL) or die("Cannot query the database to get username.<br/>");
	if($myrow = mysql_fetch_array($result))
		$UserName = $myrow["Username"];
	
	return $UserName;
}

/*
Function:	send_mail()
Updated:	09/26/2007
Description:	Makes Seed for a random number
*/
function send_mail($to, $body, $subject, $fromaddress, $fromname, $attachments=false)
{
  $eol="\r\n";
  $mime_boundary=md5(time());

  # Common Headers
  $headers .= "From: ".$fromname."<".$fromaddress.">".$eol;
  $headers .= "Reply-To: ".$fromname."<".$fromaddress.">".$eol;
  $headers .= "Return-Path: ".$fromname."<".$fromaddress.">".$eol;    // these two to set reply address
  $headers .= "Message-ID: <".time()."-".$fromaddress.">".$eol;
  $headers .= "X-Mailer: PHP v".phpversion().$eol;          // These two to help avoid spam-filters

  # Boundry for marking the split & Multitype Headers
  $headers .= 'MIME-Version: 1.0'.$eol.$eol;
  $headers .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"".$eol.$eol;

  # Open the first part of the mail
  $msg = "--".$mime_boundary.$eol;
 
  $htmlalt_mime_boundary = $mime_boundary."_htmlalt"; //we must define a different MIME boundary for this section
  # Setup for text OR html -
  $msg .= "Content-Type: multipart/alternative; boundary=\"".$htmlalt_mime_boundary."\"".$eol.$eol;

  # Text Version
  $msg .= "--".$htmlalt_mime_boundary.$eol;
  $msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
  $msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
  $msg .= strip_tags(str_replace("<br>", "\n", substr($body, (strpos($body, "<body>")+6)))).$eol.$eol;

  # HTML Version
  $msg .= "--".$htmlalt_mime_boundary.$eol;
  $msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
  $msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
  $msg .= $body.$eol.$eol;

  //close the html/plain text alternate portion
  $msg .= "--".$htmlalt_mime_boundary."--".$eol.$eol;

  if ($attachments !== false)
  {
    for($i=0; $i < count($attachments); $i++)
    {
      if (is_file($attachments[$i]["file"]))
      {  
        # File for Attachment
        $file_name = substr($attachments[$i]["file"], (strrpos($attachments[$i]["file"], "/")+1));
       
        $handle=fopen($attachments[$i]["file"], 'rb');
        $f_contents=fread($handle, filesize($attachments[$i]["file"]));
        $f_contents=chunk_split(base64_encode($f_contents));    //Encode The Data For Transition using base64_encode();
        $f_type=filetype($attachments[$i]["file"]);
        fclose($handle);
       
        # Attachment
        $msg .= "--".$mime_boundary.$eol;
        $msg .= "Content-Type: ".$attachments[$i]["content_type"]."; name=\"".$file_name."\"".$eol;  // sometimes i have to send MS Word, use 'msword' instead of 'pdf'
        $msg .= "Content-Transfer-Encoding: base64".$eol;
        $msg .= "Content-Description: ".$file_name.$eol;
        $msg .= "Content-Disposition: attachment; filename=\"".$file_name."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
        $msg .= $f_contents.$eol.$eol;
      }
    }
  }

  # Finished
  $msg .= "--".$mime_boundary."--".$eol.$eol;  // finish with two eol's for better security. see Injection.
 
  # SEND THE EMAIL
  ini_set(sendmail_from,$fromaddress);  // the INI lines are to force the From Address to be used !
  $mail_sent = mail($to, $subject, $msg, $headers);
 
  ini_restore(sendmail_from);
 
  return $mail_sent;
}

/*
Function:	swapthese(&$a, &$b)
Updated:	12/04/2007
Description:	Simple SWAP Function.
*/
function swapthese(&$a, &$b)
{
   $temp = $a;
   $a = $b;
   $b = $temp;
}


/*
Function:	AllGamesStarted($Weeknum)
Updated:	12/11/2007
Description:	Returns true if all games for the given week have started or ended.
*/
function AllGamesStarted($Weeknum, $League)
{
	$SQL = "SELECT PickEmailed FROM ".$League."Schedule Where Week=".$Weeknum." AND PickEmailed=0";
	//Open Record Set using SQL Query
	$result = mysql_query($SQL) or die("Cannot query the database to see if all games have started.<br/>");
	$numrows = mysql_num_rows($result);
	if ($numrows <= 0)
		return true;
	else
		return false;
	
}

/*
Function:	getLeagueByDate()
Updated:	03/17/2008
Description:	Returns the string abbreviation of a league based on the date of the year.
*/
function getLeagueByDate()
{
	if ((date("n") < 3) || (date("n") >= 8))
		return "NFL";
	else
		return "AFL";
}
/*
Function:	ordinal_suffix($value, $sup = 0)
Updated:	12/30/2007
Description:	Function written by Marcus L. Griswold (vujsa)
				Can be found at http://www.handyphp.com
*/
function ordinal_suffix($value, $sup = 0)
{
    is_numeric($value) or trigger_error("<b>\"$value\"</b> is not a number!, The value must be a number in the function <b>ordinal_suffix()</b>", E_USER_ERROR);
    if(substr($value, -2, 2) == 11 || substr($value, -2, 2) == 12 || substr($value, -2, 2) == 13){
        $suffix = "th";
    }
    else if (substr($value, -1, 1) == 1){
        $suffix = "st";
    }
    else if (substr($value, -1, 1) == 2){
        $suffix = "nd";
    }
    else if (substr($value, -1, 1) == 3){
        $suffix = "rd";
    }
    else {
        $suffix = "th";
    }
    if($sup){
        $suffix = "<sup>" . $suffix . "</sup>";
    }
    return $value . $suffix;
}
/*
//displays the fields and their datatypes for a table.
$link = @mysql_connect($host, $name, $pass);
if (!$link) {
   die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = $database;
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
   die('Could not set $dbname ' . mysql_error());
}
$res = mysql_query('select * from NFLSchedule', $link);
for($i=0; $i<9; $i++) {
	//echo mysql_field_name($res, $i)." is of type ".mysql_field_type($res, $i)."<BR>";
	echo mysql_field_name($res, $i)." is of type ".mysql_field_type($res, $i)."<BR>";
}
*/
?>
